package AAAA.service.Impl;


import AAAA.dao.AccountDao;
import AAAA.dao.Impl.AccountDaoImpl;
import AAAA.exception.MoneyNotEnoughException;
import AAAA.exception.transferException;
import AAAA.pojo.Account;
import AAAA.service.AccountService;
import AAAA.utils.fz;
import org.apache.ibatis.session.SqlSession;

public class AccountServiceImpl implements AccountService {

    private  AccountDaoImpl accountDao = new AccountDaoImpl();


//    private AccountDao accountDao =fz.openSession().getMapper(AccountDao.class);





    public void transfer(String fromActno, String toActno, double money) throws MoneyNotEnoughException, transferException {

        SqlSession sqlSession = fz.openSession();


        //1.判断转出账户的余额是否充足（select）
        Account fromAct = accountDao.selectByActno(fromActno);
        if (fromAct.getBalance()<money) {

        //2.如果转出账户的余额不足，提示用户
            throw  new MoneyNotEnoughException("余额不足");
        }
        //3.如果余额充足，更新转出账户的余额（update）
             //先更新内存中的java对象account的余额
        Account toAct = accountDao.selectByActno(toActno);
        fromAct.setBalance(fromAct.getBalance()-money);
        toAct.setBalance(toAct.getBalance()+money);
        //4.更新转入账户（update）
        int i = accountDao.updateByActno(fromAct);
         i+= accountDao.updateByActno(toAct);
         if (i!=2) {
             throw new transferException("转账异常，未知原因");
         }


         sqlSession.commit();
         fz.closeSession(sqlSession);



    }
}
